Captain Code: Unleash Your Coding Superpower with Python by Shmuel Forta & Ben Forta
Author:Shmuel Forta & Ben Forta [Shmuel Forta]
Language: eng
Format: epub
Publisher: Addison-Wesley Professional
Published: 2021-12-24T16:00:00+00:00
Returning Values
Now you know how to create a function and how to pass it arguments. The last thing we need to look at is how to return values from a function.
Functions can return values. Think about how you used input(). It interacted with the user and then returned whatever the user typed as the result. upper() returns the uppercase version of a string. now() returns todayâs date and time.
Your own functions will frequently need to be able to return values, too, and you can do this with the (very conveniently named) return statement.
Letâs look at an exampleâand a very useful example at that. You know what this code does, right?
num=input("Enter a number: ")
This code asks the user to Enter a number: and then stores whatever they typed into a variable named num.
So, if the user typed abc (which is definitely not a number), that will be saved into variable num. Not good.
So, hereâs a better version of the code:
Click here to view code image
num=inputNumber("Enter a number: ")
This version calls a function named inputNumber() instead of input(). Unlike input(), which will accept any text, inputNumber() is smart and makes sure the user actually types a number. Cool, huh?
Well, it would be if the inputNumber() function actually existed. But, alas, it doesnât.
But, thereâs a solution. We can create the function ourselves. Hereâs the code for Func4.py:
Click here to view code image
# Numeric input function def inputNumber(prompt): # Input variable inp = "" # Loop until variable is a valid number while not inp.isnumeric(): # Prompt for input inp = input(prompt).strip() # Return the number return int(inp) # Get a number num=inputNumber("Enter a number: ") # Display it print(num)
Save and run the code. It will prompt you for a number, which will then be displayed. If you donât type a number, itâll keep asking you to Enter a number, and wonât stop until you actually enter a number.
The last two lines of code are pretty simple. inputNumber() works just like input(). It accepts a prompt and returns a value. Here the value is saved to a variable named num, which is then printed.
The real magic is the inputNumber() function itself. We start by defining it:
# Numeric input function def inputNumber(prompt):
Just like input(), inputNumber() accepts a promptâthe text that is displayed to the userâand the prompt is passed as an argument.
Next, the code defines a variable that will store the user input:
# Input variable inp = ""
Then comes the actual prompt inside of a loop:
Click here to view code image
# Loop until variable is a valid number while not inp.isnumeric(): # Prompt for input inp = input(prompt).strip()
This is code youâve seen before. It uses a while loop with a condition that ensures that the loop will keep looping until inp is a number.
The actual input() is the same one weâve been using throughout this book. What text does input() display as a prompt? Whatever gets passed to ÂinputNumber() as an argument. prompt is a passthrough variable: You pass it to our UDF ÂinputNumber(), which passes it to the built-in function input().
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Personalized inhaled bacteriophage therapy for treatment of multidrug-resistant Pseudomonas aeruginosa in cystic fibrosis by unknow(203492)
CONSORT 2025 statement: updated guideline for reporting randomized trials by unknow(102437)
Critical evaluation of the ProfiLER-02 study design and outcomes by Vivek Subbiah & Razelle Kurzrock(101969)
Cardiac gene therapy makes a comeback by Oliver J. Müller & Susanne Hille & Anca Kliesow Remes(101767)
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(74564)
Unveiling the design rules for tunable emission in graphene quantum dots: A high-throughput TDDFT and machine learning perspective by Şener Özönder & Mustafa Coşkun Özdemir & Caner Ünlü(50975)
A yeast-based oral therapeutic delivers immune checkpoint inhibitors to reduce intestinal tumor burden by unknow(40351)
Covalent hitchhikers guide proteins to the nucleus by Alexander F. Russell & Madeline F. Currie & Champak Chatterjee(40272)
Meet the Authors: Christopher R. Mansfield and Emily R. Derbyshire by Christopher R. Mansfield & Emily R. Derbyshire(40175)
Alkaline-earth metals promote propane dehydrogenation with carbon dioxide through geometric effects: Altering the reaction pathway by unknow(32798)
Induced iron vacancies boosting FeOOH loaded on sustainable Fenton-like collagen fiber membrane for efficient removal of emerging contaminants by unknow(32591)
Efficient electric-field-assisted photochemical conversion of methane to n-propanol exclusively over penetrated TiO2Ti hollow fibers by Guanghui Feng(32511)
Bi2SiO5 nanosheets as piezo-photocatalyst for efficient degradation of 2,4-Dichlorophenol by Hangyu Shi & Yifu Li & Lishan Zhang & Guoguan Liu & Qian Zhang & Xuan Ru & Shan Zhong(32451)
A novel NDIPTA organic heterojunction photocatalyst with built-in electric field for efficient hydrogen production by Jiahui Yang & Baojun Ma & Yongfa Zhu(32426)
Enhanced conversion of methane to liquid-phase oxygenates via hollow ferrite nanotube@horseradish peroxidase based photoenzymatic catalysis by Jun Duan & Shiying Fan & Xinyong Li & Shaomin Liu(32389)
Ordered macroporous superstructure of defective carbon adorned with tiny cobalt sulfide for selective electrocatalytic hydrogenation of cinnamaldehyde by Xiao-Shi Yuan & Sheng-Hua Zhou & San-Mei Wang & Wenbo Wei & Xiaofang Li & Xin-Tao Wu & Qi-Long Zhu(32308)
What's Done in Darkness by Kayla Perrin(27225)
Topological analysis of non-conjugated ethylene oxide cored dendrimers decorated with tetraphenylethylene: Insights from degree-based descriptors using the polynomial approach by A Theertha Nair & D Antony Xavier & Annmaria Baby & S Akhila(26601)
Investigation of mechanical and self-healing properties of hydroxyl-terminated polybutadiene functionalized with 2-ureido-4-pyrimidinone by Mohsen Kazazi & Mehran Hayaty & Ali Mousaviazar(26525)